package com.shengdong.water.feature.search

import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.kongzue.dialogx.dialogs.WaitDialog
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.shengdong.water.R
import com.shengdong.water.base.BaseVMActivity
import com.shengdong.water.code.adapter.SearchAdapter
import com.shengdong.water.code.base.BaseRecyclerAdapter
import com.shengdong.water.code.base.BaseRefreshActivity
import com.shengdong.water.code.bean.Outlet
import com.shengdong.water.code.config.RouterConfig
import com.shengdong.water.code.viewmodel.SearchViewModel
import com.shengdong.water.databinding.ActivitySearchBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@Route(path = RouterConfig.SEARCH_PATH)
@AndroidEntryPoint
class SearchActivity : BaseRefreshActivity<Outlet,ActivitySearchBinding, SearchViewModel>() {


    override fun getLayoutId() = R.layout.activity_search
    override fun getViewModelClass() = SearchViewModel::class.java
    override fun getSmartRefreshLayout() = binding.refresh
    override fun getRecyclerView() = binding.recyclerSearch
    override fun getAdapter() = SearchAdapter()

    private var name: String = ""

    override fun initViews() {
        super.initViews()
        setTitle("搜索列表")
        binding.viewModel = viewModel
        name = intent.getStringExtra("name")?: ""
    }

    override fun initData() {
        super.initData()
        loadData()
    }

    override fun loadData() {
        viewModel.getOutletList(name ,currentPage, pageSize)

    }

    override fun observeData() {
        super.observeData()
        lifecycleScope.launch {
            println("NoticeActivity: 开始设置数据收集")
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                launch {
                    viewModel.outlets.collect { result ->
                        result.let {
                            if(currentPage == 1 && it.isEmpty()){
                                binding.recyclerSearch.setEmptyView(binding.layoutEmpty.root)
                                return@collect
                            }

                            if (it.isEmpty()) {
                                finishRefreshAndLoadMore(true, currentPage)
                                return@collect
                            }
                            handleData(it)
                        }
                    }

                }
            }
        }
    }


    override fun showLoading(loading: String) {
        super.showLoading(loading)
        WaitDialog.show(loading)
    }

    override fun dismissLoading() {
        super.dismissLoading()
        WaitDialog.dismiss()
    }

}